/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.lucava.boatskeeper.server.dao;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.TypedQuery;
import org.lucava.boatskeeper.shared.dto.CategoryDto;

/**
 *
 * @author glenn
 */
public class Dao<T> {

    EntityManager em;

    public Dao(EntityManager em) {
        this.em = em;
    }

    public void addEntity(T entity) {

        try {
            EntityTransaction t = em.getTransaction();
            try {
                t.begin();
                em.persist(entity);
                t.commit();
            } finally {
                if (t.isActive()) {
                    t.rollback();
                }
            }
        } finally {
            em.close();
        }
    }

    public void saveEntity(T entity) {

        try {
            EntityTransaction t = em.getTransaction();
            try {
                t.begin();
                em.persist(entity);
                t.commit();
            } finally {
                if (t.isActive()) {
                    t.rollback();
                }
            }
        } finally {
            em.close();
        }
    }

    public void deleteEntity(T entity) {

        try {
            EntityTransaction t = em.getTransaction();
            try {
                t.begin();
                em.remove(entity);
                t.commit();
            } finally {
                if (t.isActive()) {
                    t.rollback();
                }
            }
        } finally {
            em.close();
        }
    }

    public T getEntity(T entity, Integer id) {
        T result = null;
        try {
            EntityTransaction t = em.getTransaction();
            try {
                t.begin();
                result = (T) em.find(entity.getClass(), id);
                t.commit();
            } finally {
                if (t.isActive()) {
                    t.rollback();
                }
            }
        } finally {
            em.close();
        }
        return result;
    }

    public T getAllEntities(T entity, Integer id) {
        T result = null;
        try {
            EntityTransaction t = em.getTransaction();
            try {
                t.begin();

                TypedQuery<T> query =
                        em.createNamedQuery("Country.findAll", entity.getClass());
                List<T> results = query.getResultList();


                result = (T) em.find(entity.getClass(), id);
                t.commit();
            } finally {
                if (t.isActive()) {
                    t.rollback();
                }
            }
        } finally {
            em.close();
        }
        return result;
    }
}
